<template>
  <div class="dept-list">
    <div class="dept-list__top">
      <span>组织架构</span>
      <el-space>
        <el-button @click="refresh">刷新</el-button>
        <el-button @click="handleOrder">拖拽</el-button>
      </el-space>
    </div>
    <div class="dept-list__body">
      <el-tree
        ref="treeRef"
        node-key="id"
        default-expand-all
        :data="treeData"
        :props="{ label: 'name' }"
        draggable
        :allow-drag="allowDrag"
        :allow-drop="allowDrop"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        @node-contextmenu="handleContextMenu"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { deepTree } from '@/utils'
import { getSysDeptList } from '@/api/sys'

export default {
  name: 'DeptList',
  data() {
    return {
      currentNodeKey: -1,
      list: [] as any[]
    }
  },
  computed: {
    treeData() {
      return deepTree(this.list)
    }
  },
  methods: {
    async refresh() {
      this.list = await getSysDeptList()

      if (this.currentNodeKey === -1) {
        this.currentNodeKey = this.list.filter((item) => !item.parentId)[0].id
      }

      this.$nextTick(() => {
        // @ts-ignore
        this.$refs.treeRef.setCurrentKey(this.currentNodeKey)
      })
    },

    handleNodeClick(data) {
      this.currentNodeKey = data.id
    },

    handleContextMenu(event, data) {
      console.log('handleContextMenu', event, data)
    },

    // 允许拖的规则, 有父级的可以拖
    allowDrag({ data }) {
      return data.parentId
    },

    // 允许放的规则，
    allowDrop(dragNode, dropNode) {
      return dropNode.data.parentId
    },

    handleOrder() {
      console.log('handleOrder', this.treeData)

      const list = []

      function deep(arr, pid) {
        arr.forEach((item) => {
          item.parentId = pid
          list.push(item)

          if (item.children && item.children.length > 0) {
            deep(item.children, item.id)
          }
        })
      }

      deep(this.treeData, null)
      console.log('list', list)
    }
  },
  created() {
    this.refresh()
  }
}
</script>

<style scoped>
.dept-list {
  width: 300px;
  background-color: antiquewhite;
}
.dept-list__top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
  height: 40px;
}

.dept-list__body {
  padding: 10px 5px;
}

:deep(.el-tree-node__content) {
  height: 36px;
}

:deep(.is-current > .el-tree-node__content) {
  color: #4165d7;
  background-color: pink;
}
</style>
